import os
import threading

import numpy as np
import cv2
target_locations = []

# 获取最近位置的坐标
def minlocation(locations, given_location):
    min_distance = None
    min_location = None
    for location in locations:
        x1, y1 = given_location
        x2, y2 = location
        distance = abs(x1 - x2) + abs(y1 - y2)

        if min_distance is None or distance < min_distance:
            min_distance = distance
            min_location = location
    return min_location

# 获取指定坐标
def getlocationswhththread(cut_main_gray, dir):
    if not os.path.exists(dir):
        return []

    global target_locations
    target_locations = []
    img_list = os.listdir(dir)

    threads = []

    for img in img_list:
        img_gray = cv2.cvtColor(cv2.imread(dir + img), cv2.COLOR_BGR2GRAY)
        thread = threading.Thread(target=locationfunc, args=(cut_main_gray, img_gray, img))
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

    return target_locations

def locationfunc(cut_main_gray, monster_gray, img):
    global target_locations
    locations = getlocations(cut_main_gray, monster_gray)
    if len(locations) > 0:
        for location in locations:
            target_locations.append(location)

# 封装统一获取符合条件的坐标
def getlocations(main, target, score = 0.85):
    result = cv2.matchTemplate(main, target, cv2.TM_CCOEFF_NORMED)
    # 筛选结果
    locations = np.where(result >= score)
    # 将结果再次处理，仅保留坐标值
    locations = list(zip(*locations[::-1]))
    return locations
